package com.gongyinlian.personalprofilewebsiteserver.controller;

import com.gongyinlian.personalprofilewebsiteserver.common.result.Result;
import com.gongyinlian.personalprofilewebsiteserver.dto.LoginRequest;
import com.gongyinlian.personalprofilewebsiteserver.dto.RefreshTokenRequest;
import com.gongyinlian.personalprofilewebsiteserver.service.AuthService;
import com.gongyinlian.personalprofilewebsiteserver.utils.UserHolder;
import com.gongyinlian.personalprofilewebsiteserver.vo.LoginResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 
 * @author personal-profile-website
 * @date 2024-10-27
 */
@Slf4j
@Tag(name = "认证接口", description = "用户登录、登出、Token刷新等接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthService authService;
    
    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "使用用户名和密码登录系统")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        log.info("收到登录请求 - 用户名: {}", request.getUsername());
        LoginResponse response = authService.login(request);
        return Result.success("登录成功", response);
    }
    
    /**
     * 刷新Token
     */
    @Operation(summary = "刷新Token", description = "使用刷新Token获取新的访问Token")
    @PostMapping("/refresh")
    public Result<LoginResponse> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
        log.info("收到刷新Token请求");
        LoginResponse response = authService.refreshToken(request);
        return Result.success("Token刷新成功", response);
    }
    
    /**
     * 用户登出
     */
    @Operation(summary = "用户登出", description = "用户退出登录")
    @PostMapping("/logout")
    public Result<String> logout() {
        Long userId = UserHolder.getUserId();
        String username = UserHolder.getUsername();
        
        log.info("收到登出请求 - 用户名: {}, ID: {}", username, userId);
        
        if (userId == null) {
            return Result.error("未登录");
        }
        
        authService.logout(userId);
        return Result.success("登出成功");
    }
    
    /**
     * 获取当前登录用户信息
     */
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的基本信息")
    @GetMapping("/current")
    public Result<Object> getCurrentUser() {
        Long userId = UserHolder.getUserId();
        String username = UserHolder.getUsername();
        
        if (userId == null) {
            return Result.error("未登录");
        }
        
        // 构建用户信息
        return Result.success("获取成功", new Object() {
            public final Long userId = UserHolder.getUserId();
            public final String username = UserHolder.getUsername();
        });
    }
}

